import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:safetymonitor/app/components/common/no_permissions_widget.dart';
import 'package:safetymonitor/app/components/custom_app_bar.dart';
import 'package:safetymonitor/app/components/custom_refresh.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/entities/home/board/get_message_entity.dart';
import 'package:safetymonitor/generated/assets.dart';
import 'package:safetymonitor/modules/home/home_page/home_page_control.dart';
import 'package:safetymonitor/router/app_pages.dart';
import 'package:safetymonitor/app/components/dialog/exit_tips.dart';
/// 公告板
class MessageBoard extends StatefulWidget {
  const MessageBoard({super.key});

  @override
  State<MessageBoard> createState() => _MessageBoardState();
}

class _MessageBoardState extends State<MessageBoard> {
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();
  bool isNotPermissions = true;

  Future<List<GetMessageEntity>> _getData(int pageNum, int pageSize, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<GetMessageEntity>>(Interface.getNoticeList, queryParameters: {
      'pageNo': pageNum,
      'pageSize': pageSize,
    }).execute();

    if (res.isSucceed) {
      isNotPermissions = true;
      setState(() {});
      return res.data!;
    }
    res.onError((result) {
      if (result.code == 403 && result.message == '没有该操作权限') {
        isNotPermissions = false;
        setState(() {});
      }
    });
    return [];
  }

  /// 删除 id
  void del(int? id) async {
    final res = await HttpUtil().generateDeleteRequest(
      Interface.sendNotifyDelete,
      queryParameters: {'id': id},
    ).execute();
    res.onSuccess((result) {
      AppToast.showSuccess('删除成功');
      globalKey.currentState?.onRefresh();
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (!isNotPermissions) {
      return const NoPermissionsWidget();
    }
    return Scaffold(
      backgroundColor: AppColors.bg_page_color,
      appBar: CustomAppBar(
        titleText: '通知公告',
        actions: [
          //发布 这个发布按钮做成可分配，给了你权限你才有发布这个按钮
          Visibility(
            visible: Get.find<HomePageControl>().middleListAll.where((e) => e.appMenuNameCode == 'announcement').isNotEmpty,
            child: Container(
                padding: EdgeInsets.only(left: 10.w, right: 15.w, bottom: 10.w, top: 10.w),
                child: Text(
                  '发布',
                  style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w400, color: Colors.deepPurple),
                )).clickOnce(() {
              Get.toNamed(Routes.noticeBoardReleasePage)?.then((val) {
                if (val is bool) {
                  globalKey.currentState?.onRefresh();
                }
              });
            }),
          ),
        ],
      ),
      body: EasyRefresh(
        onRefresh: () {},
        child: CustomEasyRefreshList<GetMessageEntity>(
          key: globalKey,
          dataLoad: _getData,
          padding: const EdgeInsets.all(16),
          itemBuilder: (item, index) {
            return Stack(
              children: [
                Container(
                  padding: EdgeInsets.only(
                    left: 16.w,
                    right: 16.w,
                    top: 12.w,
                    bottom: 16.w,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          SvgPicture.asset(Assets.svgMessageList),
                          AppGaps.hGap10,
                          Expanded(
                            child: Text(
                              '${item.title}',
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                          AppGaps.hGap28,
                        ],
                      ),
                      AppGaps.vGap10,
                      Row(
                        children: [
                          Text(
                            '${DateTime.fromMillisecondsSinceEpoch(int.tryParse(item.createTime ?? '0') ?? 0)}',
                            style: TextStyle(
                              color: const Color(0xffC7CEE5),
                              fontSize: 14.sp,
                            ),
                          ),
                          AppGaps.hGap10,
                          Text(
                            '${item.templateNickname}',
                            style: TextStyle(
                              color: const Color(0xffC7CEE5),
                              fontSize: 14.sp,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ).click(() {
                  Get.toNamed(Routes.noticeBoardDetail, arguments: item)?.then((_) {
                    setState(() {
                      //在点击的时候就去掉新消息
                      item.readStatus = true;
                    });
                  });
                }),
                Positioned(
                  top: 0,
                  right: 0,
                  child: Visibility(
                    visible: !(item.readStatus ?? true),
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        SvgPicture.asset(Assets.svgRightNew),
                        Text(
                          'NEW',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 11.sp,
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                Positioned(
                  bottom: 0,
                  right: 0,
                  child: Visibility(
                    //删除 这个删除按钮做成可分配，给了你权限你才有删除这个按钮
                    visible: Get.find<HomePageControl>().middleListAll.where((e) => e.appMenuNameCode == 'announcement').isNotEmpty,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        SvgPicture.asset(Assets.svgRightNew),
                        Text(
                          '删除',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 11.sp,
                          ),
                        )
                      ],
                    ),
                  ).clickOnce(() {
                    Get.dialog<bool>(ExitTips(
                      content: '是否确定删除？',
                      func: (v) {
                        if (v) {
                          del(item.id);
                        }
                      },
                    ));
                  }),
                )
              ],
            );
          },
        ),
      ),
    );
  }
}
